/*
	Copyright (c) 2008, Grant Jones <grant@podtronics.com>.
	All rights reserved.

	Redistribution and use in source and binary forms, with or
	without modification, are permitted provided that the following
	conditions are met:

		Redistributions of source code must retain the above copyright
		notice, this list of conditions and the following disclaimer.
		
		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in
		the documentation and/or other materials provided with the
		distribution.
		
		Neither the name of the gxjones.com nor the names of its
		contributors may be used to endorse or promote products derived
		from this software without specific prior written permission.
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
	OF THE POSSIBILITY OF SUCH DAMAGE.
	
	http://www.opensource.org/licenses/bsd-license.php
*/

/*
 *  edb_domain_delete.c
 *  scatterd
 *
 *  Created by Grant Jones on 3/11/08.
 *
 */

#include "edb_main.h"
#include "edb_msg_parser.h"
#include "edb_msg_utils.h"
#include "strmap.h"
#include "edb_domain.h"
#include "edb_domain_insert.h"
#include "edb_domain_select.h"
#include "edb_domain_index.h"

/* delete is very similar to insert */
void edb_domain_delete( edb_domain_ref_t *dref, AttrList *delete_what,  Expr *where_expr, cmapStruct *result_items )
{
//	AttrList *name_only = edbAppendAttrListFromPool( result_items->mempool, NULL, edbCreateAttrValueCStrFromPool(result_items->mempool, "_name", NULL) );
	int err_code = 0;
	rtvalue_t key, data;
	int affect_count = 0;
		
	cmapStruct *s_result = cmap_new(result_items->mempool);
	cmapEnumStruct attr_items_e;
	CMAP_KEY_TYPE item_num;
	AttrList *attrs_out;

	/* allocate result spaces for 3 attributes: result, error, affect_count or result, _name, affect_count */
	edb_net_item_t *ri = edb_add_result( result_items, 3 );	
	if(!ri)
		return;	


	/* select all item parts, for unindexing */
	edb_domain_select_base( dref, NULL, where_expr, /*groupby*/NULL, /*having_arg*/NULL, /*orderby_arg*/NULL, /*limit_arg*/NULL, s_result );

	/* zero the key we are returning, this for the case when
	** no key is affected */
	key.size = 0;
	key.data = NULL;


	if( edb_domain_begin( dref ) < 0 )
		goto cleanup;


	cmap_enum(s_result, &attr_items_e);

	while( (attrs_out = cmap_enum_next(&attr_items_e, &item_num)) )
	{	
		strmapEnumStruct e;
		char *attr_key;
		size_t attr_key_sz;
		AttrValue *replace_val_ptr ;
		
		if( delete_what )
		{
			AttrValue *name_val_ptr = strmap_lookup( attrs_out, EDB_NAME_KEY, strlen(EDB_NAME_KEY) );
			
			strmap_enum(delete_what, &e);
			
			/* remove keys that are to be deleted from attrs_out */
			while( (replace_val_ptr = strmap_enum_next(&e, &attr_key, &attr_key_sz)) )
			{
				if( attr_key_sz == strlen(EDB_NAME_KEY) && memcmp( attr_key, EDB_NAME_KEY, strlen(EDB_NAME_KEY) ) == 0 )
					continue;	/* can't remove the _name key */
				
				strmap_remove(attrs_out, attr_key, attr_key_sz);
				
				/* remove the index */
				rtvalue_t ak = { replace_val_ptr->key.n, (void *)replace_val_ptr->key.z };
				rtvalue_t av = { replace_val_ptr->value.n, (void *)replace_val_ptr->value.z };
				rtvalue_t item_name = { name_val_ptr->value.n, (void *)name_val_ptr->value.z };
				
				if( edb_domain_rm_index(dref->d, &ak, &av, &item_name) )
				{
					printf("edb_domain_index_item failed to index\n");
				}
			}

			edb_domain_construct_item( &data, attrs_out );
			key.data = (unsigned char *)name_val_ptr->value.z;
			key.size = name_val_ptr->value.n;

			/* use the root _name index: */
			rtree_use( dref->d->rt_db_ptr, NULL, 0 );			/* position list cursor at root */
			rtree_use( dref->d->rt_db_ptr, dref->d->dname, dref->d->dname_sz );
			rtree_use( dref->d->rt_db_ptr, EDB_NAME_KEY, strlen(EDB_NAME_KEY) );		
			
			if( rt_put( dref->d->rt_db_ptr, &key, &data ) )
			{
				err_code = EDB_ERR_DOMAIN_PUT_FAIL;
				goto cleanup;
			}

			/* here we update our sync table, only if we aren't inserting into the sync table */
			edb_domain_notify_sync( dref, &key );

		}
		else
		{
			
			AttrValue *name_val_ptr = strmap_lookup( attrs_out, EDB_NAME_KEY, strlen(EDB_NAME_KEY) );
			key.data = (unsigned char *)name_val_ptr->value.z;
			key.size = name_val_ptr->value.n;
			
			/* use the root _name index: */
			rtree_use( dref->d->rt_db_ptr, NULL, 0 );			/* position list cursor at root */
			rtree_use( dref->d->rt_db_ptr, dref->d->dname, dref->d->dname_sz );			
			rtree_use( dref->d->rt_db_ptr, EDB_NAME_KEY, strlen(EDB_NAME_KEY) );		
			
			rt_del(dref->d->rt_db_ptr, &key, 1);
			
			/* here we update our sync table, only if we aren't inserting into the sync table */
			edb_domain_notify_sync( dref, &key );			
			
			/* remove all indexing for this item */
			edb_domain_unindex_item( dref, attrs_out, &key );
		}
		affect_count++;

	}
	err_code = edb_domain_end( dref );	
	
	
	
cleanup:

	if( err_code == 0  )
	{
		ri->attr_count = 0;
		edb_term_result_attr( result_items->mempool, &ri->attrs[ri->attr_count], EDB_RESULT_KEY, EDB_RESULT_VALUE_OK );
		ri->attr_count ++;
		
		edb_term_result_attr( result_items->mempool, &ri->attrs[ri->attr_count], EDB_AFFECT_COUNT_KEY, "%d", affect_count);
		ri->attr_count ++;
		
		if( key.size > 0 )
		{
			edb_malloc_result_attr( result_items->mempool,  &ri->attrs[ri->attr_count], EDB_NAME_KEY, strlen(EDB_NAME_KEY), key.size );
			memcpy( ri->attrs[ri->attr_count].value, key.data, key.size );
			ri->attr_count ++;
		}
	}
	else
	{
		ri->attr_count = 0;
		edb_term_result_attr( result_items->mempool, &ri->attrs[ri->attr_count], EDB_RESULT_KEY, EDB_RESULT_VALUE_FAILURE );
		ri->attr_count ++;
		
		edb_term_result_attr( result_items->mempool, &ri->attrs[ri->attr_count], EDB_ERROR_KEY, "%d", err_code );
		ri->attr_count ++;

		edb_term_result_attr( result_items->mempool, &ri->attrs[ri->attr_count], EDB_AFFECT_COUNT_KEY, "%d", affect_count);
		ri->attr_count ++;
		
	}
}



